package com.fivetalks.client;

import java.io.UnsupportedEncodingException;
import java.util.Vector;

import org.apache.http.HttpEntity;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import com.fivetalks.client.JoinFormActivity.GetAsyncTask;
import com.fivetalks.network.Definition;

import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class LoginFormActivity extends Activity implements OnClickListener{
	EditText etEmail;
	EditText etPassword;
	Button btSubmit;
	String email;
	String password;
	
	private final String URL =  Definition.URL_ROOT + "/member/login";
//	private final String URL =  "http://10.201.208.180:8080/myproject/test";
//	private final String URL =  "http://192.168.0.27:8080/myproject/member/join";
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
	    super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login_form);
        Intent intent = getIntent();
        email = intent.getStringExtra("email");
        password = intent.getStringExtra("password");
        etEmail = (EditText)findViewById(R.id.etEmail);
        etPassword = (EditText)findViewById(R.id.etPassword);
        etEmail.setText(email);
        etPassword.setText(password);
        btSubmit = (Button)findViewById(R.id.btSubmit);
        btSubmit.setOnClickListener(this);
	}
	
	public void onClick(View v)
	{
		switch (v.getId()) {
		case R.id.btSubmit:
			email = etEmail.getText().toString();
	        password = etPassword.getText().toString();
			etEmail.setText(email);
	        etPassword.setText(password);
			
			GetAsyncTask gat = new GetAsyncTask();
			gat.execute(URL);
			break;
		}
	}
	
	class GetAsyncTask extends AsyncTask<String,Integer,String> {
		Vector<BasicNameValuePair> nameValue=new Vector<BasicNameValuePair>();
		//String...은 개수가 여러개 가변적으로 받아들이고 params에 배열로 저장
		//백그라운드로 동작할 메소드
		//보통시간이 오래걸리는 작업.
		protected String doInBackground(String... params){
//			Log.i("getApp","doInBackground");
			nameValue.add(new BasicNameValuePair("email", email));
			nameValue.add(new BasicNameValuePair("password", password));
			String result=null;
			try{
				result = sendData(params[0]);
//				Log.i("getApp",result);
	    	}catch (Exception e){
					e.printStackTrace();
			}
			return result;
		}
		//doInBackground메소드가 수행된 결과를 받아들여서 수행된다.
		@Override
		protected void onPostExecute(String result){
			super.onPostExecute(result);
			
//			Log.i("getApp","onPostExecute");
			int index_start= result.indexOf("<login_check>", 0);
			int index_end= result.indexOf("</login_check>", 0);
//			Log.i("getApp","index: "+index_start);
//			Log.i("getApp","index: "+index_end);
			nameValue.clear();
			if(true==(result.substring(index_start, index_end).contains("true")))
			{
				
				Toast.makeText(LoginFormActivity.this, R.string.login_form_login_ok, Toast.LENGTH_SHORT).show();
				Intent intent = new Intent(LoginFormActivity.this, MainFrameActivity.class);
				intent.putExtra("email", email);
				intent.putExtra("password", password);
				intent.putExtra("status", "all"); // 고친다.
				startActivity(intent);
			}
			else
			{
				Toast.makeText(LoginFormActivity.this, R.string.login_form_login_notok, Toast.LENGTH_SHORT).show();
			}
			
		}
		public String sendData(String url) throws Exception {

			HttpPost request = makeHttpPost(url);

			HttpClient client = new DefaultHttpClient();
			ResponseHandler<String> reshandler = new BasicResponseHandler();
			String result = client.execute(request, reshandler);
			
			return result;

		}
	    
		private HttpPost makeHttpPost(String url) throws Exception {
			HttpPost request = new HttpPost(url);
	 
			request.setEntity(makeEntity(nameValue));

			return request;
		}

		private HttpEntity makeEntity(Vector<BasicNameValuePair> nameValue) throws Exception {
			HttpEntity result = null;
			try {
				result = new UrlEncodedFormEntity(nameValue,"UTF-8");
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
			return result;
		}
		
	}
}
